<template>
  <div class="container">
    <el-row class="section">
      <el-col :span="12" class="section-title">{{
        $t('user_overview')
      }}</el-col>
      <el-col :span="12" class="section-toolbar">
        <el-button-group>
          <el-button
            :type="dateType == 1 ? 'primary' : ''"
            size="small"
            @click="setDateType('1')"
            >{{ $t('day') }}</el-button
          >
          <el-button
            :type="dateType == 2 ? 'primary' : ''"
            size="small"
            @click="setDateType('2')"
            >{{ $t('week') }}</el-button
          >
          <el-button
            :type="dateType == 3 ? 'primary' : ''"
            size="small"
            @click="setDateType('3')"
            >{{ $t('month') }}</el-button
          >
        </el-button-group>
      </el-col>
    </el-row>
    <el-card shadow="hover" class="section-card">
      <el-row v-if="UserData.twoData">
        <el-col :xl="3" :lg="4" :md="6" :sm="8">
          <i class="el-icon-user-solid user" />
          <p>【{{ timeOpt['time_' + dateType] }}】</p>
          <p v-if="dateType == 2">
            {{ UserData.twoData[1].date }} ~ {{ weekDay }}
          </p>
          <p v-else-if="dateType == 1">
            {{ UserData.twoData[1].date }} ~ {{ UserData.twoData[1].date }}
          </p>
          <p v-else>
            {{ UserData.twoData[1].date + '-01' }} ~
            {{ `${UserData.twoData[1].date}-${weekDay}` }}
          </p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="8">
          <p>{{ $t('cumulative_users') }}</p>
          <p class="number">{{ UserData.totalUserCount }}</p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="8">
          <p>{{ $t('active_user') }}</p>
          <p class="number">{{ UserData.activeUsers }}</p>
          <p class="compare">
            <span
              v-if="UserData.activeUsersPer"
              :style="{
                color: UserData.activeUsersPer < 0 ? '#4CAF50' : '#F44336'
              }"
              class="key"
            >
              <i
                :class="
                  UserData.activeUsersPer < 0
                    ? 'el-icon-caret-bottom'
                    : 'el-icon-caret-top'
                "
              />
              {{ Math.abs(UserData.activeUsersPer) }} %
            </span>
            <span v-else>--</span>
            {{ comDateOpt['comDate_' + dateType] }}
          </p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="8">
          <p>{{ $t('new_users') }}</p>
          <p class="number">{{ UserData.newUsers }}</p>
          <p class="compare">
            <span
              v-if="UserData.newUsersPer"
              :style="{
                color: UserData.newUsersPer < 0 ? '#4CAF50' : '#F44336'
              }"
              class="key"
            >
              <i
                :class="
                  UserData.newUsersPer < 0
                    ? 'el-icon-caret-bottom'
                    : 'el-icon-caret-top'
                "
              />
              {{ Math.abs(UserData.newUsersPer) }} %
            </span>
            <span v-else>--</span>
            {{ comDateOpt['comDate_' + dateType] }}
          </p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="10">
          <p>{{ $t('the_average_frequency_of_users_using_the_app') }}</p>
          <p class="number">{{ UserData.twoData[1].avgUserCount }}</p>
          <p class="compare">
            <span
              v-if="UserData.avgUserCountPer"
              :style="{
                color: UserData.avgUserCountPer < 0 ? '#4CAF50' : '#F44336'
              }"
              class="key"
            >
              <i
                :class="
                  UserData.avgUserCountPer < 0
                    ? 'el-icon-caret-bottom'
                    : 'el-icon-caret-top'
                "
              />
              {{ Math.abs(UserData.avgUserCountPer) }} %
            </span>
            <span v-else>--</span>
            {{ comDateOpt['comDate_' + dateType] }}
          </p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="10">
          <p>{{ $t('the_average_duration_of_users_using_the_app') }}(s）</p>
          <p class="number">{{ UserData.twoData[1].avgUserSecond }}</p>
          <p class="compare">
            <span
              v-if="UserData.avgUserSecondPer"
              :style="{
                color: UserData.avgUserSecondPer < 0 ? '#4CAF50' : '#F44336'
              }"
              class="key"
            >
              <i
                :class="
                  UserData.avgUserSecondPer < 0
                    ? 'el-icon-caret-bottom'
                    : 'el-icon-caret-top'
                "
              />
              {{ Math.abs(UserData.avgUserSecondPer) }} %
            </span>
            <span v-else>--</span>
            {{ comDateOpt['comDate_' + dateType] }}
          </p>
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="hover" class="section-card">
      <el-row v-if="UserData.twoData">
        <el-col :xl="3" :lg="4" :md="6" :sm="8">
          <i class="el-icon-user-solid menber" />
          <p>【{{ timeOpt['time_' + dateType] }}】</p>
          <p v-if="dateType == 2">
            {{ UserData.twoData[1].date }} ~ {{ weekDay }}
          </p>
          <p v-else-if="dateType == 1">
            {{ UserData.twoData[1].date }} ~ {{ UserData.twoData[1].date }}
          </p>
          <p v-else>
            {{ UserData.twoData[1].date + '-01' }} ~
            {{ `${UserData.twoData[1].date}-${weekDay}` }}
          </p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="8">
          <p>{{ $t('cumulative_members') }}</p>
          <p class="number">{{ UserData.totalMemberCount }}</p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="8">
          <p>{{ $t('active_member') }}</p>
          <p class="number">{{ UserData.activeMember }}</p>
          <p class="compare">
            <span
              v-if="UserData.activeMemberPer"
              :style="{
                color: UserData.activeMemberPer < 0 ? '#4CAF50' : '#F44336'
              }"
              class="key"
            >
              <i
                :class="
                  UserData.activeMemberPer < 0
                    ? 'el-icon-caret-bottom'
                    : 'el-icon-caret-top'
                "
              />
              {{ Math.abs(UserData.activeMemberPer) }} %
            </span>
            <span v-else>--</span>
            {{ comDateOpt['comDate_' + dateType] }}
          </p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="8">
          <p>{{ $t('new_member') }}</p>
          <p class="number">{{ UserData.newMember }}</p>
          <p class="compare">
            <span
              v-if="UserData.newMemberPer"
              :style="{
                color: UserData.newMemberPer < 0 ? '#4CAF50' : '#F44336'
              }"
              class="key"
            >
              <i
                :class="
                  UserData.newMemberPer < 0
                    ? 'el-icon-caret-bottom'
                    : 'el-icon-caret-top'
                "
              />
              {{ Math.abs(UserData.newMemberPer) }} %
            </span>
            <span v-else>--</span>
            {{ comDateOpt['comDate_' + dateType] }}
          </p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="8">
          <p>{{ $t('new_member_by_invited') }}</p>
          <p class="number">{{ UserData.twoData[1].childNewCount }}</p>
          <p class="compare">
            <span
              v-if="UserData.childNewCountPer"
              :style="{
                color: UserData.childNewCountPer < 0 ? '#4CAF50' : '#F44336'
              }"
              class="key"
            >
              <i
                :class="
                  UserData.childNewCountPer < 0
                    ? 'el-icon-caret-bottom'
                    : 'el-icon-caret-top'
                "
              />
              {{ Math.abs(UserData.childNewCountPer) }} %
            </span>
            <span v-else>--</span>
            {{ comDateOpt['comDate_' + dateType] }}
          </p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="10">
          <p>{{ $t('the_average_frequency_of_members_using_the_app') }}</p>
          <p class="number">{{ UserData.twoData[1].avgMemberCount }}</p>
          <p class="compare">
            <span
              v-if="UserData.avgMemberCountPer"
              :style="{
                color: UserData.avgMemberCountPer < 0 ? '#67C23A' : '#F44336'
              }"
              class="key"
            >
              <i
                :class="
                  UserData.avgMemberCountPer < 0
                    ? 'el-icon-caret-bottom'
                    : 'el-icon-caret-top'
                "
              />
              {{ Math.abs(UserData.avgMemberCountPer) }} %
            </span>
            <span v-else>--</span>
            {{ comDateOpt['comDate_' + dateType] }}
          </p>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="10">
          <p>{{ $t('the_average_duration_of_members_using_the_app') }}(s）</p>
          <p class="number">{{ UserData.twoData[1].avgMemberSecond }}</p>
          <p class="compare">
            <span
              v-if="UserData.avgMemberSecondPer"
              :style="{
                color: UserData.avgMemberSecondPer < 0 ? '#4CAF50' : '#F44336'
              }"
              class="key"
            >
              <i
                :class="
                  UserData.avgMemberSecondPer < 0
                    ? 'el-icon-caret-bottom'
                    : 'el-icon-caret-top'
                "
              />
              {{ Math.abs(UserData.avgMemberSecondPer) }} %
            </span>
            <span v-else>--</span>
            {{ comDateOpt['comDate_' + dateType] }}
          </p>
        </el-col>
      </el-row>
    </el-card>
    <el-row :gutter="10">
      <el-col :sm="12">
        <el-card shadow="hover" class="section-card">
          <div slot="header">
            <span class="echart-title"
              >【{{ dateTypeOpt['dateType_' + dateType] }}】
              {{ $t('active_user') }}
              ({{ $t('users') }})
            </span>
            <br />
            <span class="echart-time"
              >{{ ActiveUsers.dateRange }} | {{ $t('past')
              }} {{ dateTypeOpt['dateType_' + dateType] }}</span
            >
          </div>
          <div id="ActiveUsers" class="echart-body menu" />
        </el-card>
      </el-col>
      <el-col :sm="12">
        <el-card shadow="hover" class="section-card">
          <div slot="header">
            <span class="echart-title"
              >【{{ dateTypeOpt['dateType_' + dateType] }}】
              {{ $t('new_users') }}
              ({{ $t('users') }})
            </span>
            <br />
            <span class="echart-time "
              >{{ NewUsers.dateRange }} | {{ $t('past')
              }} {{ dateTypeOpt['dateType_' + dateType] }}</span
            >
          </div>
          <div id="NewUsers" class="echart-body menu" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import echarts from 'echarts';
import {
  getActiveUserMemberCount,
  getNewMemberCount,
  getUserData
} from '@/api/data-overview.js';
import textFormatting from '@/utils/textFormatting.js';
import '@/assets/css/common/style.scss';

export default {
  data() {
    return {
      dateType: 1,
      activeUsersEchart: null,
      newUsersEchart: null,
      timeOpt: {
        time_1: this.$t('yesterday'),
        time_2: this.$t('last_week'),
        time_3: this.$t('last_month')
      },
      comDateOpt: {
        comDate_1: this.$t('compared_to_last_week'),
        comDate_2: this.$t('compared_to_last_week'),
        comDate_3: this.$t('compared_to_last_month')
      },
      dateTypeOpt: {
        dateType_1: this.$t('a_7_days'),
        dateType_2: this.$t('a_7_weeks'),
        dateType_3: this.$t('a_6_months')
      },
      ActiveUsers: {
        dateRange: '',
        date: [],
        memberActiveCount: [],
        userActiveCount: [],
        legend: [this.$t('active_user'), this.$t('active_member')]
      },
      NewUsers: {
        dateRange: '',
        date: [],
        memberActiveCount: [],
        userActiveCount: [],
        legend: [this.$t('new_users'), this.$t('new_member')]
      },
      UserData: {},
      weekDay: ''
    };
  },

  computed: {
    isOpenMenu() {
      return this.$store.state.app.sidebar.opened; // 监听菜单是否展开
    }
  },

  watch: {
    isOpenMenu(newVal) {
      if (newVal) {
        document.getElementById('ActiveUsers').classList.add('menu-open');
        document.getElementById('ActiveUsers').classList.add('menu-open');
        setTimeout(() => {
          this.activeUsersEchart.resize();
          this.newUsersEchart.resize();
        }, 500);
      } else {
        document.getElementById('ActiveUsers').classList.remove('menu-open');
        document.getElementById('ActiveUsers').classList.remove('menu-open');
      }
    }
  },

  mounted() {
    this.getActiveUsers();
    this.getNewUsers();
    this.getUserDataList();
    window.addEventListener('resize', () => {
      this.activeUsersEchart.resize();
      this.newUsersEchart.resize();
    });
  },

  methods: {
    setDateType(type) {
      this.dateType = type;
      this.getActiveUsers();
      this.getNewUsers();
      this.getUserDataList();
    },
    getUserDataList() {
      getUserData({ dateType: this.dateType })
        .then(result => {
          if (result.code == 200) {
            const data = {};
            [
              'avgMemberCount',
              'avgMemberSecond',
              'avgUserCount',
              'avgUserSecond',
              'childNewCount'
            ].forEach(item => {
              data[`${item}Per`] =                result.data.twoData[0][item] == 0
                  ? undefined
                  : textFormatting.fomatFloat(
                      ((result.data.twoData[1][item]
                        - result.data.twoData[0][item])
                        / result.data.twoData[0][item])
                        * 100,
                    2
                    );
            });

            this.UserData = Object.assign(
              result.data,
              {
                activeUsers: this.UserData.activeUsers,
                newUsers: this.UserData.newUsers,
                activeMember: this.UserData.activeMember,
                newMember: this.UserData.newMember,
                activeUsersPer: this.UserData.activeUsersPer,
                newUsersPer: this.UserData.newUsersPer,
                activeMemberPer: this.UserData.activeMemberPer,
                newMemberPer: this.UserData.newMemberPer
              },
              data
            );
            this.weekDay =              this.dateType == 2
                ? textFormatting.getNextDate(this.UserData.twoData[1].date, 6)
                : '';
            const date = new Date();
            this.weekDay =              this.dateType == 3
                ? new Date(date.getFullYear(), date.getMonth(), 0).getDate()
                : this.weekDay;
          } else {
            this.$message.error(result.msg);
          }
        })
        .catch(() => {});
    },

    getActiveUsers() {
      this.activeUsersEchart = echarts.init(
        document.getElementById('ActiveUsers')
      );
      this.activeUsersEchart.showLoading();
      getActiveUserMemberCount({ dateType: this.dateType })
        .then(result => {
          if (result.code == 200) {
            this.ActiveUsers = {
              dateRange: '',
              date: [],
              memberActiveCount: [],
              userActiveCount: [],
              legend: [this.$t('active_user'), this.$t('active_member')]
            };
            result.data.forEach((item, index) => {
              if (index != 0 || this.dateType != 1) {
                // 取最近7天/最近7周/最近6个月
                this.ActiveUsers.date.push(item.date);
                this.ActiveUsers.memberActiveCount.push(item.memberActiveCount);
                this.ActiveUsers.userActiveCount.push(item.userActiveCount);
              }
            });
            const { length } = result.data;
            if (length > 5) {
              // 计算活跃用户/活跃会员 对比百分比
              let oneMem = 0;
              let twoMem = 0;
              let oneUser = 0;
              let twoUser = 0;
              // 按天计算和周月不一致
              if (this.dateType == 1) {
                // 获取活跃用户/活跃会员 数据
                this.UserData.activeUsers = this.ActiveUsers.userActiveCount[
                  length - 2
                ];
                this.UserData.activeMember = this.ActiveUsers.memberActiveCount[
                  length - 2
                ];
                oneUser = result.data[0].userActiveCount;
                oneMem = result.data[0].memberActiveCount;
              } else {
                this.UserData.activeUsers = this.ActiveUsers.userActiveCount[
                  length - 1
                ];
                this.UserData.activeMember = this.ActiveUsers.memberActiveCount[
                  length - 1
                ];
                oneUser = result.data[length - 2].userActiveCount;
                oneMem = result.data[length - 2].memberActiveCount;
              }
              twoUser = result.data[length - 1].userActiveCount;
              twoMem = result.data[length - 1].memberActiveCount;
              this.UserData.activeUsersPer =                oneUser == 0
                  ? undefined
                  : textFormatting.fomatFloat(
                    ((twoUser - oneUser) / oneUser) * 100,
                      2
                  );
              this.UserData.activeMemberPer =                oneMem == 0
                  ? undefined
                  : textFormatting.fomatFloat(
                      ((twoMem - oneMem) / oneMem) * 100,
                    2
                    );
            }
            if (result.data.length > 0) {
              const date = new Date();
              this.weekDay =                this.dateType == 3
                  ? new Date(date.getFullYear(), date.getMonth(), 0).getDate()
                  : this.weekDay;
              this.ActiveUsers.dateRange =                this.dateType != 3
                  ? `${this.ActiveUsers.date[0]} ~ ${
                      this.ActiveUsers.date[this.ActiveUsers.date.length - 1]
                  }`
                  : `${`${this.ActiveUsers.date[0]}-01`} ~ ${
                      this.ActiveUsers.date[this.ActiveUsers.date.length - 1]
                  }-${this.weekDay}`;
            } else {
              this.ActiveUsers.dateRange = this.$t('no_data_available');
            }

            this.activeUsersEchart.hideLoading();
            this.activeUsersEchart.setOption(
              this.getEchartOptions(
                this.ActiveUsers.date,
                this.ActiveUsers.legend,
                this.ActiveUsers.userActiveCount,
                this.ActiveUsers.memberActiveCount
              )
            );
          } else {
            this.activeUsersEchart.hideLoading();
            this.$message.error(result.msg);
          }
        })
        .catch(() => {
          this.activeUsersEchart.hideLoading();
        });
    },

    getNewUsers() {
      this.newUsersEchart = echarts.init(document.getElementById('NewUsers'));
      this.newUsersEchart.showLoading();
      getNewMemberCount({ dateType: this.dateType })
        .then(result => {
          if (result.code == 200) {
            this.NewUsers = {
              dateRange: '',
              date: [],
              newMemberCount: [],
              newUserCount: [],
              legend: [this.$t('new_users'), this.$t('new_member')]
            };
            result.data.forEach((item, index) => {
              if (index != 0 || this.dateType != 1) {
                // 取最近7天/最近7周/最近6个月
                this.NewUsers.date.push(item.date);
                this.NewUsers.newMemberCount.push(item.newMemberCount);
                this.NewUsers.newUserCount.push(item.newUserCount);
              }
            });
            const { length } = result.data;
            if (length > 5) {
              // 计算新增用户/新增会员 对比百分比
              let oneMem = 0;
              let twoMem = 0;
              let oneUser = 0;
              let twoUser = 0;
              // 按天计算和周月不一致
              if (this.dateType == 1) {
                this.UserData.newUsers = this.NewUsers.newUserCount[length - 2];
                this.UserData.newMember = this.NewUsers.newMemberCount[
                  length - 2
                ];
                oneUser = result.data[0].newUserCount;
                oneMem = result.data[0].newMemberCount;
              } else {
                this.UserData.newUsers = this.NewUsers.newUserCount[length - 1];
                this.UserData.newMember = this.NewUsers.newMemberCount[
                  length - 1
                ];
                oneUser = result.data[length - 2].newUserCount;
                oneMem = result.data[length - 2].newMemberCount;
              }
              twoUser = result.data[length - 1].newUserCount;
              twoMem = result.data[length - 1].newMemberCount;

              this.UserData.newUsersPer =                oneUser == 0
                  ? undefined
                  : textFormatting.fomatFloat(
                      ((twoUser - oneUser) / oneUser) * 100,
                    2
                    );

              this.UserData.newMemberPer =                oneMem == 0
                  ? undefined
                  : textFormatting.fomatFloat(
                    ((twoMem - oneMem) / oneMem) * 100,
                    2
                  );
            }
            // 获取时间段
            this.NewUsers.dateRange =              result.data.length > 0
                ? `${this.NewUsers.date[0]} ~ ${
                  this.NewUsers.date[this.NewUsers.date.length - 1]
                }`
                : this.$t('no_data_available');
            if (result.data.length > 0) {
              const date = new Date();
              this.weekDay =                this.dateType == 3
                  ? new Date(date.getFullYear(), date.getMonth(), 0).getDate()
                  : this.weekDay;
              this.NewUsers.dateRange =                this.dateType != 3
                  ? `${this.NewUsers.date[0]} ~ ${
                      this.NewUsers.date[this.NewUsers.date.length - 1]
                    }`
                  : `${`${this.NewUsers.date[0]}-01`} ~ ${
                      this.NewUsers.date[this.NewUsers.date.length - 1]
                  }-${this.weekDay}`;
            } else {
              this.NewUsers.dateRange = this.$t('no_data_available');
            }

            this.newUsersEchart.hideLoading();
            this.newUsersEchart.setOption(
              this.getEchartOptions(
                this.NewUsers.date,
                this.NewUsers.legend,
                this.NewUsers.newUserCount,
                this.NewUsers.newMemberCount
              )
            );
          } else {
            this.newUsersEchart.hideLoading();
            this.$message.error(result.msg);
          }
        })
        .catch(() => {
          this.newUsersEchart.hideLoading();
        });
    },

    getEchartOptions(xAxis, legend, data1, data2) {
      return {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: legend
        },
        grid: {
          left: '40',
          right: '40',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxis
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: legend[0],
            type: 'line',
            data: data1
          },
          {
            name: legend[1],
            type: 'line',
            data: data2
          }
        ]
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.ActiveUsers,
.NewUsers {
  width: 100%;
  &-open {
    width: 99%;
  }
}
</style>
